import time
from datetime import datetime
from threading import Thread

from .utils import SerialConn

DRY_BOX_PORT = "/dev/ttyUSB0"


class DryBox(SerialConn):
    def __init__(self, gcmd, interval=10, port=DRY_BOX_PORT, baudrate=19200):
        self.gcmd = gcmd
        self.interval = interval
        super().__init__(port, baudrate)
        self.last_msg = None
        self.last_msg_time = None

    def start_read_data_to_log(self):
        Thread(target=self._read_data_to_log).start()

    def _read_data_to_log(self):
        help.log("初始化干燥盒模块")
        while True:
            if not self.conn or self.conn.closed:
                try:
                    self.open()
                except Exception as e:
                    help.log(f"DryBox.read_data_to_log {e}")
            try:
                if self.conn and not self.conn.closed:
                    data = self.conn.readline()
                    if data:
                        data = data.decode()
                        # self.gcmd.respond_info(f"干燥盒原始信息:{data}")
                        lines = data.split("\n")
                        if len(lines) > 1:
                            self.last_msg = lines[-2]
                            self.last_msg_time = str(datetime.now())
                            self.gcmd.respond_info(f"干燥盒信息:{self.last_msg}")
            except Exception as e:
                help.log(f"读取干燥盒数据失败 {e}")
            time.sleep(self.interval)
